package com.mao.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@Component
public class ImageUD {
    @Value("${chuotuan.path}")
    private String basePath;
    public String upload(MultipartFile file){
        //获取文件的后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //UUID生成的随机名称再拼接文件后缀名
        String fileName = UUID.randomUUID().toString()+suffix;
        //创建目录对象
        File dir = new File(basePath);
        //判断目录是否存在
        if (!dir.exists()){
            //不存在则创建
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public void download(String name, HttpServletResponse response){

        try {
            //输入流通过输入流读取文件
            FileInputStream fileInputStream=new FileInputStream(basePath+name);

            //输出流，通过输出流写到前端浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            //设置返回的数据类型为图片
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes =new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            //先关闭写，再关闭读的资源
            outputStream.close();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
